import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/live/live_chat_logic.dart';
import 'package:ball_lion/utils/mode_config.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:ball_lion/entity/match/detail/lq_detail_head_entity.dart';
import 'package:ball_lion/entity/match/match_live_entity.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/utils/app_config.dart';
import 'package:ball_lion/module/match_detail/match_views_page.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:ball_lion/server/api/basketball_api.dart';
import 'package:ball_lion/server/api/live_api.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/match_detail/basketball/lq_detail_data_view.dart';
import 'package:ball_lion/module/match_detail/basketball/lq_detail_outs_widget.dart';
import 'package:ball_lion/module/match_detail/basketball/lq_info_widget.dart';
import 'package:ball_lion/module/match_detail/basketball/lq_lineup_widget.dart';
import 'package:ball_lion/module/match_detail/basketball/lq_odds_view.dart';
import 'package:ball_lion/module/match_detail/live/live_chat_view.dart';
import 'package:ball_lion/module/match_detail/live/live_source_sheet.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/module/live/ali_live_logic.dart';
import 'package:ball_lion/widgets/player/qs_player_logic.dart';

class LqMatchDetailLogic extends GetxController
    with GetTickerProviderStateMixin {
  int matchId = Get.arguments;
  LqDetailHeadInfoEntity? detail;
  final scrollC = ApmScrollController();
  RxDouble opacity = (1.0).obs;
  bool showTitle = false;
  bool isLoading = true;
  late TabController tabController;
  List<String> tabsClick = [
    Constant.guandian,
    Constant.baoliao,
    Constant.model
  ];
  Timer? t;
  List<String> tabs = [];
  List<Widget> pages = [];
  late bool _isFocus = User.basketballFocuses.isFocus(matchId);
  String currentTab = '';

  bool get isFocus => _isFocus;

  bool _isPlayVideo = false;
  String matchLiveInfo = "";
  MatchLiveEntity? _liveInfo;
  List<MatchLiveEntity>? roomList;
  bool get isPlayVideo => _isPlayVideo;
  MatchLiveEntity? get liveInfo => _liveInfo;

  set liveInfo(MatchLiveEntity? value) {
    _liveInfo = value;
    update();
  }

  set isPlayVideo(bool value) {
    _isPlayVideo = value;
    update();
  }

  set isFocus(bool value) {
    _isFocus = value;
    update();
  }

  @override
  void onInit() async {
    super.onInit();
    tabController = TabController(length: tabs.length, vsync: this);
    scrollC.addListener(() {
      double opa = 1 - scrollC.offset / scrollC.position.maxScrollExtent;
      if (opa < 0) {
        opacity.value = 0;
      } else if (opa > 1) {
        opacity.value = 1;
      } else {
        opacity.value = opa;
      }
      final show = scrollC.offset >= scrollC.position.maxScrollExtent - 5;
      if (show != showTitle) {
        showTitle = show;
        update();
      }
    });
    Get.put(QsPlayerLogic(), tag: "$matchId");
    await playLive();
    await getData();
    // getVideoList();
    t = Timer.periodic(const Duration(seconds: 30), (timer) {
      if ((detail?.statusId ?? 0) > 1 && (detail?.statusId ?? 0) < 10) {
        getData();
      }
    });
  }

  Future getVideo() async {
    final result =
        await OtherApi.getVideoList(Get.arguments, 2, Get.parameters['roomId']);
    if (result != null) {
      roomList = result;
    }
  }

  Future playLive() async {
    await getVideo();
    var index = roomList?.indexWhere((element) =>
        element.roomId.hasValue &&
        element.roomId == Get.parameters['roomId'].toInt());
    if (Get.parameters['roomId'].hasValue) {
      if (index == -1 || index == null) {
        index = 0;
        var info =
            await LiveApi.getLiveDetail(Get.parameters['roomId']!.toInt());
        Get.dialog(
            QsDialog.single(info?.status == 2 ? "专家直播已结束" : "主播暂未开始直播，请耐心等待"));
        return;
      }
      await setLiveStream(true, roomInfo: roomList![index]);
    } else {
      index = roomList?.indexWhere((element) => element.defaultPlay == 1);
      if (index != null && index != -1) {
        MatchLiveEntity live = roomList![index];
        shouldAutoPlay(live);
      }
    }
  }

  Future shouldAutoPlay(MatchLiveEntity? live) async {
    await setLiveStream(true, roomInfo: live);
    try {
      LiveChatLogic chatLogic =
          Get.find<LiveChatLogic>(tag: "${live?.matchId}");
      chatLogic.getRefresh();
    } catch (e) {
      log("");
    }
    try {
      QsPlayerLogic playerLogic =
          Get.find<QsPlayerLogic>(tag: "${live?.matchId}");
      playerLogic.url = live?.url ?? "";
      playerLogic.doRefresh();
    } catch (e) {
      log("");
    }
  }

  Future setLiveStream(bool videoPlay, {MatchLiveEntity? roomInfo}) async {
    liveInfo = roomInfo;
    // try {
    //   Get.delete<QsPlayerLogic>(tag: "${liveInfo?.roomId}");
    // } catch (e) {
    //   log("");
    // }
    // try {
    //   Get.put(QsPlayerLogic(), tag: "${liveInfo?.roomId}");
    // } catch (e) {
    //   log("");
    // }
    isPlayVideo = videoPlay;
    makeTabcontroller();
    update();
  }

  Future getData() async {
    detail = await BasketballApi.lqMatchDetailHead(matchId);
    if (detail?.homeTeamName.hasValue == true &&
        detail?.awayTeamName.hasValue == true) {
      matchLiveInfo =
          "${detail?.homeTeamName ?? ""} VS ${detail?.awayTeamName ?? ""}";
      try {
        Get.find<AliLiveLogic>(tag: "$matchId").matchInfo = matchLiveInfo;
      } catch (e) {
        log(e.toString());
      }
    }
    try {
      makeTabcontroller();
    } catch (e) {
      log(e.toString());
    }
    update();
  }

  makeTabcontroller() {
    //info	情报	boolean	injure	伤禁	boolean	lineup	阵容(统计)	boolean
    //live	赛况	boolean	odds	指数	boolean	plan	方案  booleandata	数据	boolean
    tabs = [];
    pages = [];
    if (liveInfo?.roomId.hasValue ?? false) {
      tabs.add(Constant.zhibojian);
      pages.add(LiveChatView(matchId: matchId));
    }
    if (detail?.live == true) {
      tabs.add(Constant.saikuang);
      pages.add(LqDetailOutsWidget(id: matchId));
    }
    // if (detail?.injure == true) {
    //   tabs.add(Constant.shangjin);
    //   pages.add(LqLineupWidget(matchId: matchId));
    // }
    if (detail?.lineup == true) {
      tabs.add(Constant.tongji);
      pages.add(LqLineupWidget(matchId: matchId));
    }
    if (detail?.data == true) {
      tabs.add(Constant.shuju);
      pages.add(LqDetailDataView(matchId: matchId));
    }
    if (ModeConfig.matchTabs) {
      if (detail?.plan == true) {
        tabs.add(Constant.guandian);
        pages.add(MatchViewsPage(matchId: matchId));
      }
      if (detail?.info == true) {
        tabs.add(Constant.baoliao);
        pages.add(const LqInfoWidget());
      }
    }
    if (detail?.odds == true &&
        AppConfig.config.showOdds &&
        ModeConfig.matchDetailOdds) {
      tabs.add(Constant.zhishu);
      pages.add(const LqOddsView());
    }
    int idx = 0;
    if (Get.parameters['tabName'].hasValue) {
      idx = tabs.indexWhere((e) => e == Get.parameters['tabName']!);
    } else {
      if (detail?.video == 1 && roomList?.first.expertId.hasValue == true) {
        idx = tabs.indexWhere((e) => e == Constant.zhibojian);
      } else if (detail?.statusId == 1) {
        if (detail?.planCnt != 0 && detail?.planCnt != null) {
          idx = tabs.indexWhere((e) => e == Constant.guandian);
        } else {
          idx = tabs.indexWhere((e) => e == Constant.shuju);
        }
      } else {
        idx = tabs.indexWhere((e) => e == Constant.tongji);
      }
    }
    if (currentTab.isNotEmpty) {
      idx = tabs.indexWhere((e) => e == currentTab);
    }
    if (idx < 0 || idx >= tabs.length) {
      idx = 0;
    }
    if (tabsClick.contains(tabs[idx])) {
      SpUtils.setMatchClick(tabs[idx], "$matchId");
    }
    tabController.dispose();
    tabController =
        TabController(length: tabs.length, vsync: this, initialIndex: idx);
    tabController.addListener(() {
      currentTab = tabs[tabController.index];
      if (tabsClick.contains(tabs[tabController.index])) {
        SpUtils.setMatchClick(tabs[tabController.index], "$matchId");
      }
      update();
    });
    isLoading = false;
    update();
  }

  onTapLive([bool isLive = true]) async {
    Utils.onEvent('bsxq_dhzb');
    if (roomList.noValue) {
      await getVideo();
    }
    if (roomList.hasValue) {
      int? index;
      if (isLive) {
        index = await LiveSourceSheet.show(
            liveList:
                roomList?.where((element) => element.vtype != 4).toList() ?? [],
            select: liveInfo?.expertId);
      } else {
        index = roomList?.indexWhere((element) => element.vtype == 4);
      }
      if (index != null) {
        MatchLiveEntity live = roomList![index];
        if (isLive && !live.playStatus.hasValue) {
          Toast.text("暂未开始直播，请耐心等待");
          return;
        }
        if (live.vformat == 'URL') {
          launchUrlString(live.url ?? '',
              mode: LaunchMode.externalApplication,
              webViewConfiguration:
                  const WebViewConfiguration(enableDomStorage: false));
        } else {
          if (live.copyright == 0) {
            setLiveStream(true, roomInfo: live);
            try {
              LiveChatLogic chatLogic =
                  Get.find<LiveChatLogic>(tag: "${live.matchId}");
              chatLogic.getRefresh();
            } catch (e) {
              log("");
            }
            try {
              QsPlayerLogic playerLogic =
                  Get.find<QsPlayerLogic>(tag: "${live.matchId}");
              playerLogic.url = live.url ?? "";
              playerLogic.doRefresh();
            } catch (e) {
              log("");
            }
          } else {
            Toast.text('暂无版权，请选择其他直播源');
          }
        }
      }
    }
  }
}
